import './common/base.scss'
import 'bootstrap/dist/css/bootstrap.min.css'
import './sass/car.scss'


import axios from 'axios';

getCartList()
// 渲染购物车
function render() {
    let data = JSON.parse(localStorage.getItem('cartList'))
    let ul = document.querySelector('.center ul')
    ul.innerHTML = data.map(item => {
        return `<li>
        <div class="col-1">
          <input type="checkbox" class='checkbox' ${item.is_select=='1'?'checked':''} goods_id=${item.goods_id} />
        </div>
        <div class="col-1">
          <img
            src="${item.goods_big_logo
            }"
            alt=""
          />
        </div>
        <h3 class="col-5">${item.goods_name}</h3>
        <div class="col-1">
          <span>￥</span>
          <b>${item.goods_price}</b>
        </div>
        <div class="btn-group btn-group-sm col-2">
          <button type="button" class="btn btn-secondary del" goods_id=${item.goods_id}>-</button>
          <button type="button" class="btn btn-secondary">${item.cart_num}</button>
          <button type="button" class="btn btn-secondary add" goods_id=${item.goods_id}>+</button>
        </div>
        <div class="col-1">
          <span>￥</span>
          <b>${item.goods_price*item.cart_num}</b>
        </div>
        <div class="col-1">
          <button>X</button>
        </div>
      </li>`
    }).join(' ')
    tPrice()
}

// 事件委托
let jd_container = document.querySelector('.jd-container')
jd_container.addEventListener('click', async (e) => {
    let cartList = JSON.parse(localStorage.getItem('cartList'))
    let allChecked = document.querySelector('.allChecked')
    let checkboxs = document.querySelectorAll('.checkbox')
    // 全选
    if (e.target.classList.contains('allChecked')) {
        cartList.forEach(item => {
            item.is_select = e.target.checked ? '1' : '0'
        })
        localStorage.setItem('cartList', JSON.stringify(cartList))
        render()
    }
    // 点击了子元素
    else if (e.target.classList.contains('checkbox')) {
        let goodsId = e.target.getAttribute('goods_id')
        cartList.forEach(item => {
            if (item.goods_id == goodsId) {
                item.is_select = e.target.checked ? '1' : '0'
            }
        })
        localStorage.setItem('cartList', JSON.stringify(cartList))
        otherCheck()
        tPrice()

    }
    //  点击了删减
    else if (e.target.classList.contains('del')) {
        let carList=JSON.parse(localStorage.getItem('cartList'))
        let obj=carList.find(item=>{
            if(item.goods_id == e.target.getAttribute('goods_id')){
                return item
            }
        })
        console.log(obj.cart_num-1);
        if(obj.cart_num-1<1){
            alert('1为最小单位，如需删除，请点击删除按钮')
            return
        }
        let data = await axios({
            url: `/api/car/delGoods/${e.target.getAttribute('goods_id')}`,
            headers: {
                'authorization': localStorage.getItem('token'),
            }
        })
       
        let data2 = await axios({
            url: '/api/car/carData',
            headers: {
                'authorization': localStorage.getItem('token')
            }
        })
        console.log(data.data.num);
        console.log(data2);
        localStorage.setItem('cartList',JSON.stringify(data2.data.data))
        render()

        //    let {data}= await axios({
        //         url:`/api/car/getCart_num/${e.target.getAttribute('goods_id')}`,
        //         headers: {
        //             'authorization': localStorage.getItem('token'),
        //         }
        //     })
        //     console.log(data.num);
        //     let cartList = JSON.parse(localStorage.getItem('cartList'))
        //    let obj= cartList.find(item => {
        //         if (item.goods_id == e.target.getAttribute('goods_id')) {
        //             console.log(item.cart_num);
        //             return item
        //         }
        //     })
        //     cartList.forEach(item=>{
        //         if (item.goods_id == e.target.getAttribute('goods_id')) {
        //             item.cart_num--

        //         }
        //     })

        //     console.log(obj.cart_num);
        //     localStorage.setItem('cartList',JSON.stringify(cartList))
        //     if (obj.cart_num >0) {
        //         await axios({
        //             url: `/api/car/addGoods/${e.target.getAttribute('goods_id')}`,
        //             headers: {
        //                 'authorization': localStorage.getItem('token'),
        //             }
        //         })
        //     } else {
        //         alert('数量1是最小单位，如需删除，请点删除按钮')
        //     }
        //     render()

    }

})
// 子checkbox点击时判断是否需要全选
function otherCheck() {
    let allChecked = document.querySelector('.allChecked')
    let data = JSON.parse(localStorage.getItem('cartList'))
    let arr = []
    data.forEach((item, index) => {
        arr[index] = item.is_select
    })
    let flag = arr.every(item => {
        return item == '1'
    })
    if (flag) {
        allChecked.checked = flag
    } else {
        allChecked.checked = false
    }
}
// 总价
function tPrice() {
    let cartList = JSON.parse(localStorage.getItem('cartList'))
    let arr = cartList.filter(item => {
        return item.is_select == '1'
    })
    let total = arr.reduce((pre, item) => {
        return pre + item.cart_num * item.goods_price
    }, 0)
    let tPrice = document.querySelector('.tPrice span:nth-child(2)')
    tPrice.innerHTML = total
};
// 获取cartList数据
async function getCartList() {
    let data = await axios({
        url: '/api/car/carData',
        headers: {
            'authorization': localStorage.getItem('token')
        }
    })
    if (data.data.code == 400) {
        alert(data.msg)
        return
    }
    console.log(data.data.data);
    localStorage.setItem('cartList', JSON.stringify(data.data.data))
    render()
}